# coding=utf8
import uplink
import protocol.term

__author__ = 'lijian'
import logging
import lamp
import threading
import time
import setting
import config
import rtu
import event
import platform

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s:%(filename)s[line:%(lineno)d] : %(message)s',
                    filemode='w')

monitorThreads = []



# console = logging.StreamHandler()
# console.setLevel(logging.DEBUG)
# formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
# console.setFormatter(formatter)
# logging.getLogger('').addHandler(console)

def loadData():
    config.readConfig()

    lamp.manager.loadLamps()
    lamp.manager.loadAutoTasks()
    lamp.manager.loadPlanTask()

    rtu.manager.loadData()

    event.loadEvents()


def startMonitor():
    lamp.monitor.startMonitor()
    lamp.task.start()
    rtu.monitor.startMonitor()
    event.startMonitor()

    uplink.keepAlive()


if __name__ == '__main__':
    logging.info("shanghai rtu,version:%d" % setting.version)

    config.checkRuntime()

    if platform.machine()!="armv5tejl":
        rtu.mock.start()

    rtu.monitor.RtuMonitor.GetInstance().reset()
    if not rtu.action.getExternalTime():
        logging.error("sync external time error!")
        exit()

    loadData()

    startMonitor()

    # event=threading.Event()
    while True:
        time.sleep(1)
        # packet=protocol.term.packet.Packet(ctrl=1,data=[0x61,0x14])
        # plc.send(packet,[0,0,0,0,1],True)






